package top.jiangqiang.qianyi.data.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import top.jiangqiang.qianyi.common.auth.SessionHolder;

import java.time.LocalDateTime;

@Component
@Slf4j
public class MybatisPlusMetaHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            LocalDateTime time = LocalDateTime.now();
            Long userId = SessionHolder.currentUser().getUserId();
            insertFillIfNull(metaObject, "createUser", Long.class, userId);
            insertFillIfNull(metaObject, "updateUser", Long.class, userId);
            insertFillIfNull(metaObject, "createTime", LocalDateTime.class, time);
            insertFillIfNull(metaObject, "updateTime", LocalDateTime.class, time);
            insertFillIfNull(metaObject, "deleted", Long.class, 0L);
            insertFillIfNull(metaObject, "version", Integer.class, 0);
        } catch (Exception e) {
            log.error("自动注入失败:{}", e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            LocalDateTime time = LocalDateTime.now();
            Long userId = SessionHolder.currentUser().getUserId();
            insertFillIfNull(metaObject, "updateUser", Long.class, userId);
            updateFillIfNull(metaObject, "updateTime", LocalDateTime.class, time);
        } catch (Exception e) {
            log.error("自动注入失败:{}", e.getMessage());
        }
    }

    /**
     * @param metaObject metaObject
     * @param fieldName  字段名
     * @param fieldType  类型
     * @param value      值
     * @param <T>        泛型
     * @param <E>        T的子类
     */
    private <T, E extends T> void insertFillIfNull(MetaObject metaObject, String fieldName, Class<T> fieldType, E value) {
        log.debug("自动插入：{}，值：{}", fieldName, value);
        strictInsertFill(metaObject, fieldName, fieldType, value);
    }

    /**
     * @param metaObject metaObject
     * @param fieldName  字段名
     * @param fieldType  类型
     * @param value      值
     * @param <T>        泛型
     * @param <E>        T的子类
     */
    private <T, E extends T> void updateFillIfNull(MetaObject metaObject, String fieldName, Class<T> fieldType, E value) {
        log.debug("自动插入：{}，值：{}", fieldName, value);
        strictUpdateFill(metaObject, fieldName, fieldType, value);
    }
}
